package top.infopub.mgr.fia.web;


import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.fia.domain.ArPlanDomain;
import top.infopub.mgr.fia.service.ArPlanService;
import top.infopub.mgr.fia.vo.ArPlanVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.fia.ArPlan;
import top.infopub.model.fia.ArPlanDetail;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.DisclosePro;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 应收款计划管理
 * @author wangw
 * @version 2020年1月15日
 * @see ArPlanController
 * @since
 */
@Controller
@RequestMapping("/arPlan")
public class ArPlanController extends GenericFlowController {

    @Autowired
    private ArPlanService arPlanService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private DiscloseProService discloseProService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 应收款计划列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
        request.setAttribute("bindOrgId", bindOrgId);
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            OrgInfo orgInfo = new OrgInfo();
            orgInfo.setState(1);
            orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "fia/lay-arPlan-list";
    }

    /**
     * 应收款计划列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ArPlanDomain> queryDataByCondition(ArPlanVo arPlanVo, ParamPage paramPage) {
        Page<ArPlanDomain> page = new Page<ArPlanDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (arPlanVo.getEndDate() != null) {
            arPlanVo.setEndDate(DateUtils.addDays(arPlanVo.getEndDate(), 1));
        }
        page = arPlanService.selectPageByDomainWhere(page, arPlanVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 应收款计划-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可应收款计划的应收款计划记录
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            OrgInfo orgInfo = new OrgInfo();
            orgInfo.setState(1);
            orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        //所有已交底的项目
        List<DisclosePro> disclosePros = discloseProService.selectByEntityWhere(new DisclosePro());
        request.setAttribute("disclosePros", disclosePros);
        return "fia/lay-arPlan-add";
    }

    /**
     * 根据id查询应收款计划详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 应收款计划Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        ArPlanVo arPlan = arPlanService.selectById(id);
        map.put("arPlan", arPlan);
        return new ModelAndView("fia/lay-arPlan-detail", map);
    }

    /**
     * 新增应收款计划
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request, ArPlanVo arPlan) {

        if (StringUtils.isBlank(arPlan.getId())) {
            int count = arPlanService.count(arPlan.getBelongsYear(),arPlan.getProCode());
            //判断是否存在同一公司名称、同一预算年度已有生效中单据
            if (count > 0) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("已有同一公司同一预算年度单据，不可重复提交");
            }
        }

        String[] months = request.getParameterValues("months");//子项月份
        String[] backCashs = request.getParameterValues("backCash");//子项-回购款
        String[] omIncomes = request.getParameterValues("omIncome");//子项-项目运维收入

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();

        /**
         * 应收款计划主表处理
         */
        String id = IdFactory.getUUIDUpper();
        arPlan.setId(id);
        arPlan.setHrStaffApplyId(vo.getHrStaffId());
        arPlan.setAddBy(vo.getId());
        arPlan.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("fia_ar_plan_codes");
        arPlan.setCodes(codes);
        // 处理processId
        //arPlan.setProcessId(IdFactory.getUUIDUpper());
        arPlan.setProcessStatus("9");//生效
        arPlan.setUptBy(vo.getId());
        arPlan.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //子项处理
        List<ArPlanDetail> arPlanDetails = new ArrayList<ArPlanDetail>();
        for (int i = 0; i < months.length; i++ ) {
            String orderId = months[i];
            ArPlanDetail arPlanDetail = new ArPlanDetail();
            String subId = IdFactory.getUUIDUpper();//自动生成主键
            arPlanDetail.setId(subId);
            arPlanDetail.setArPlanId(id);
            arPlanDetail.setMonths(Integer.parseInt(orderId));
            arPlanDetail.setBackCash(new BigDecimal(backCashs[i]));
            arPlanDetail.setOmIncome(new BigDecimal(omIncomes[i]));
            arPlanDetail.setAddBy(vo.getId());
            arPlanDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            arPlanDetails.add(arPlanDetail);
        }

        arPlanService.addArPlan(arPlan, arPlanDetails);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
            "应收款计划 -新增应收款计划：项目名称=" + arPlan.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 修改应收款计划状态
     * @param 
     * @return 
     * @see
     */
    @RequestMapping("/updateStatus")
    public @ResponseBody RspVo<String> updateStatus(String id) {
        ArPlan plan = arPlanService.selectByPrimaryKey(id);
        String oldStatus = plan.getProcessStatus();
        String newStatus = "9";
        if ("9".equals(oldStatus)) {
            newStatus = "10";
        }
        else {
            newStatus = "9";
        }
        plan.setProcessStatus(newStatus);
        plan.setUptTime(new Date());
        plan.setUptBy(SessionUserUtils.getSessionUserId());
        arPlanService.updateBySelective(plan);
        // 操作日志
        LogUtil.bizLog(LogUtil.LogModelType.OTHER, LogUtil.AcctionType.UPDATE,
            "修改状态  应收款计划表单据ID:" + plan.getCodes(), "");
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑应收款计划表
     * @param payBillVo
     * @return 
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @see
     */
    @RequestMapping("/update")
    public @ResponseBody RspVo<ArPlanVo> update(ArPlanVo arPlanVo) {
        arPlanService.udpArPlan(arPlanVo);
        LogUtil.bizLog(LogModelType.OTHER, AcctionType.UPDATE,
            "修改应收款计划表 - 应收款计划表Id:" + arPlanVo.getId(), null);
        return RspVo.getSuccessResponse(arPlanVo);
    }

}
